package com.fwmagic.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fwmagic.springcloud.entities.CommonResult;
import com.fwmagic.springcloud.entities.Payment;
import com.fwmagic.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @description:
 * @author: fangwei
 * @date: 2022/5/5
 **/
@RestController
@Slf4j
public class CircleBreakerController {

    @Value("${server-url.nacos-user-service}")
    private String serverURL;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback",
            fallback = "handlerFallback",//只负责业务异常
            blockHandler = "blockHandler",//只负责sentinel控制台配置违规
            exceptionsToIgnore = {IllegalArgumentException.class} //忽略指定异常
    )

    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult result = restTemplate.getForObject(serverURL + "/paymentSQL/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常。");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该 id 没有记录，空指针异常。");
        }
        return result;
    }

    public CommonResult<Payment> handlerFallback(Long id, Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444, "异常兜底 handlerFallback 内容 " + e.getMessage(), payment);
    }

    public CommonResult<Payment> blockHandler(Long id, BlockException exception) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(445, "blockHandler-sentinel 限流,无此流水。 " + exception.getMessage(), payment);
    }

    // OpenFeign
    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/openfeign/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
        if (id == 4) {
            throw new RuntimeException("没有该id:"+id);
        }
        return this.paymentService.paymentSQL(id);
    }

}
